package com.zs.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * AQS源码中lock方法和unlock方法，这两个方法主要是用来解决并发中互斥的问题
 *
 * @author madison
 * @description
 * @date 2021/5/26 11:49
 */
public class ReentrantLockTest {
    private ReentrantLock lock = new ReentrantLock();
    Object object = new Object();

    public static void main(String[] args) {
        ReentrantLockTest test = new ReentrantLockTest();
        new Thread(() -> test.testMethod(), "threadA").start();
        new Thread(() -> test.testMethod(), "threadB").start();
//        new Thread(() -> test.testMethod()).start();
    }

    public void testMethod() {
//        synchronized (object) {
        try {
            lock.lock();
            System.out.println("threadName -> " + Thread.currentThread().getName() + " lock");
            TimeUnit.SECONDS.sleep(5);
            System.out.println("threadName -> " + Thread.currentThread().getName() + " unlock");
            lock.unlock();
            System.out.println("threadName -> " + Thread.currentThread().getName() + " exit testMethod");
        } catch (Exception e) {
            e.printStackTrace();
        }
//        }
    }
}
